package com.ruoyi.bus.wechat;

import com.ruoyi.bus.http.OkHttp;
import com.ruoyi.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class WechatQrCodeUtil {

    private static String createwxaqrcodeUrl = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=";//获取applets永久二维码地址


    public static InputStream getBusQRImage(Long busId){
        return getQRImage(busId, null, 2);//使用用户小程序信息
    }


    /**
     * @Description 获取小程序二维码图片
     * @Author caiyanshan  2
     * @Param []
     * @Return java.nio.Buffer
     */
    private static InputStream getQRImage(Long param1, Long param2,Integer type){
        String url = createwxaqrcodeUrl + WechatTokenUtils.getAccessToken(type);
        StringBuffer paramBuffer = new StringBuffer();
        //paramBuffer.append("");
        //paramBuffer.append(param1.toString());
/*        if(param2 != null) {
            paramBuffer.append("&");
            paramBuffer.append("param2=" + param2);
        }*/
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("page", "Mmine/pages/Verifyidentity/index");
        paramMap.put("scene", param1);
        byte[] bytes = OkHttp.syncPostCommon(url, paramMap).toBytes();
        InputStream in = new ByteArrayInputStream(bytes);
        //printInputStream(in);
        return in;
    }


    /**
     * 打印小程序返回流信息
     * @param in
     */
    private static void printInputStream(InputStream in){
        try {
            //<1>创建字节数组输出流，用来输出读取到的内容
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            //<2>创建缓存大小
            byte[] buffer = new byte[1024]; // 1KB
            //每次读取到内容的长度
            int len = -1;
            //<3>开始读取输入流中的内容
            while ((len = in.read(buffer)) != -1) { //当等于-1说明没有数据可以读取了
                baos.write(buffer, 0, len);   //把读取到的内容写到输出流中
            }
            //<4> 把字节数组转换为字符串
            String content = baos.toString();
            baos.close();
            //<6>返回字符串结果
            if(StringUtils.isNotEmpty(content)){
                if(content.equals("errCode")){
                    log.error("request wechat qr code , return date is : " + content);
                }
            }
            log.error("request wechat qr code , return date is : " + content);
        } catch (Exception e) {
            log.info("request wechat qr code find error , the error is : " + e.getMessage());
        }
    }

}
